package com.swjd.huffmantree;

import java.util.ArrayList;
import java.util.Collections;

/**
 * 创建赫夫曼树
 */
public class HuffmanTree {
    public static void main(String[] args) {
        int arr[] = {13, 7, 8, 3, 29, 6, 1};
        Node huffmanTreeRoot = createHuffmanTree(arr);
        preOrder(huffmanTreeRoot);
    }

    /**
     * 创建赫夫曼树
     *
     * @param arr 需要被创建的数组
     * @return 创建完成后的根节点
     */
    public static Node createHuffmanTree(int[] arr) {
        //遍历arr
        ArrayList<Node> nodes = new ArrayList<>();
        for (int value : arr) {
            nodes.add(new Node(value));
        }
        while (nodes.size() > 1) {
            //对集合进行排序 从小到大
            Collections.sort(nodes);
            System.out.println(nodes);

            //取出权值最小的两颗二叉树
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);

            //构建新二叉树
            Node parent = new Node(leftNode.value + rightNode.value);
            parent.left = leftNode;
            parent.right = rightNode;
            //删除掉之前处理过的两个二叉树
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            //将新二叉树加入
            nodes.add(parent);
        }
        //返回头结点
        return nodes.get(0);
    }

    public static void preOrder(Node root) {
        if (root != null) {
            root.preOrder();
        } else {
            System.out.println("空树");
        }
    }
}

/**
 * 节点类
 * 实现Comparable进行排序
 */
class Node implements Comparable<Node> {
    int value;//节点权值
    Node left;//左子节点
    Node right;//右子节点

    //前序遍历
    public void preOrder() {
        System.out.println(this);
        if (this.left != null) {
            this.left.preOrder();
        }
        if (this.right != null) {
            this.right.preOrder();
        }
    }

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        //从小到大排序
        return this.value - o.value;
    }
}